

//
//  BFAudioRecorder.m
//  beifang
//
//  Created by Apple on 17/4/21.
//  Copyright © 2017年 郭凯. All rights reserved.
//

#import "BFAudioRecorder.h"

@interface BFAudioRecorder()<AVAudioRecorderDelegate>
@property (nonatomic,strong) AVAudioRecorder *audioRecorder;//音频录音机
@end

@implementation BFAudioRecorder
/**
 *  获得录音机对象
 *
 *  @return 录音机对象
 */
-(AVAudioRecorder *)audioRecorder{
    if (!_audioRecorder) {
        //创建录音文件保存路径
        NSString *url=[self getSavePath];
        self.audioPath = url;
        NSLog(@"url = %@",url);
        //创建录音格式设置
        NSDictionary *setting=[self getAudioSetting];
        //创建录音机
        NSError *error=nil;
        _audioRecorder=[[AVAudioRecorder alloc]initWithURL:[NSURL URLWithString:url] settings:setting error:&error];
        _audioRecorder.delegate=self;
        if (error) {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}


// 视频存放的url
-(NSString *)getSavePath{
    NSString *timeName = [NSString stringWithFormat:@"%.0f",[[NSDate date] timeIntervalSince1970]];
    NSString *name = [NSString stringWithFormat:@"%@.caf",timeName];
    //获取缓存的文件夹
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES).lastObject;
    NSString *path = [NSString stringWithFormat:@"%@/%@",cachesPath,name];
    return path;
}

/**
 *  取得录音文件设置
 *
 *  @return 录音设置
 */
-(NSDictionary *)getAudioSetting{
    NSMutableDictionary *dicM=[NSMutableDictionary dictionary];
    //设置录音格式 aac格式
    [dicM setObject:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    [dicM setObject:@(44100) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:@(1) forKey:AVNumberOfChannelsKey];
    //每个采样点位数,分为8、16、24、32
    [dicM setObject:@(16) forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [dicM setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    
    return dicM;
}

/**开始录音*/
-(void)startRecord{
    if (!self.audioRecorder.isRecording) {
        [self.audioRecorder record];
    }
}
/**取消录制*/
-(void)cancelRecord{
    [self.audioRecorder stop];
    [self.audioRecorder deleteRecording];
}

/**暂停录制*/
-(void)pasueRecord{
    [self.audioRecorder pause];
}

/**恢复录音*/
-(void)resumeRecord{
    [self.audioRecorder record];
}

/**结束录音*/
-(void)stopRecord{
    [self.audioRecorder stop];
     self.audioRecorder = nil;
}
/**录制的代理方法*/
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    NSLog(@"完成录音");
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error{
    NSLog(@"录音编码错误=%@",error);
    
}
@end
